package TAIC.IPLM;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Scanner;

import javax.imageio.ImageIO;

public class ShowCodes {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		if ( args.length != 1) {
			System.out.println ( "please input the size of top codes to show") ;
			return ;
		}
		( new ShowCodes ()).work( args ) ;
	}

	private void work ( String args [] ) throws Exception{
		int topK = Integer.valueOf( args [ 0 ] ) ;
		String dir = "codeDir\\" ;
		String showDir = "codeDir\\show\\" ;
		makeDir ( showDir ) ;
		Scanner scanner = new Scanner ( new File ( dir + "stat.txt")) ;
		for ( int i = 0 ; i < topK ; i ++ ) {
			String number = scanner.next() ;
			scanner.next() ;
			copyImage ( dir + "codes\\" + number + ".jpg", showDir + i + ".jpg" ) ;
		}
	}
	
	private void copyImage ( String fileName, String output ) throws Exception {
		int R = 11 ;
		int r =  5 ;
		BufferedImage img = ImageIO.read( new File ( fileName )) ;
		BufferedImage bi = new BufferedImage ( 2 * r + 1, 2 * r + 1, BufferedImage.TYPE_3BYTE_BGR );
		for ( int i = - r ; i <= r ; i ++ )
			for ( int j = -r ; j <= r ; j ++ )
				bi.setRGB(i + r , j + r ,img.getRGB( R + i - 1, R + j - 1)) ;
		Rescale ( bi ) ; 
		ImageIO.write(bi, "jpg", new File ( output )) ;
	}
	
	private void Rescale ( BufferedImage img ) {
		int r = 5 ;
		int min = 255 ;
		int max = -255 ; 
		for ( int i = -r ; i <= r ; i ++ ) 
			for ( int j = -r ; j <= r ; j ++ ) {
				int red = img.getRGB ( r + i, r + j ) & 0xff;
				if ( red < min ) min = red;
				if ( red > max ) max = red ;
			}
		
		int intervel = max - min ;
		for ( int i = -r ; i <= r ; i ++ ) 
			for ( int j = -r ; j <= r ; j ++ ) {
				int red = img.getRGB ( r + i , r + j ) & 0xff;
				red = (int)( (double)( red - min ) / intervel * 255 );
				int color = ( red << 16 ) + ( red << 8 ) + red ;
				img.setRGB( r + i, r + j , color ) ;
			}
	}
	
	
	private void makeDir ( String dirName ) {
		File dir = new File ( dirName ) ;
		if ( ! dir.exists() ) dir.mkdirs() ; 
	}	
}
